// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

var NetworkManager = require('NetworkManager')
var ClickManager = require('ClickManager')

var emailItem = cc.Class({
    name: 'emailItem',
    properties: {
        isUnread: 0,
        id: 0,
        createTime: '',
        msg: ''
    }
});

cc.Class({
    extends: cc.Component,

    properties: {
        emtilItems: {
            default: [],
            type: emailItem
        },

        itemPrefab: cc.Prefab,
        emailMsgNode: cc.Node,

        deletedNode: cc.Node,
        readNode: cc.Node
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        // 一键删除
        ClickManager.onClick(this.deletedNode, this.deletedNode, () => {
            NetworkManager.doEmailDeleted('all')
            this.getEmailData()
        })

        // 一键删除
        ClickManager.onClick(this.readNode, this.readNode, () => {
            NetworkManager.doEmailRead('all')
            this.getEmailData()
        })
    },

    // 模态框显示时
    onEnable () {
        this.getEmailData()
    },

    // 获取邮件数据
    getEmailData () {
        var token = cc.sys.localStorage.getItem('__TOKEN__')
        this.emailMsgNode.removeAllChildren()

        try {
            NetworkManager.onConnectedToHall( (hallService) => {
                hallService.proxy.getAllEmail(token, (data) => {
                    var list = JSON.parse(data.datas)

                    this.emailMsgNode.height = list.length
                    for (let i in list) {
                        let obj = {
                            id: list[i].id,
                            isUnread: list[i].is_unread,
                            createTime: list[i].create_time,
                            msg: list[i].msg
                        }

                        var item = cc.instantiate(this.itemPrefab)
                        this.emailMsgNode.addChild(item)
                        item.getComponent('EmailItemList').init(obj)
                    }
                })
            })
        } catch (err) {
            console.log('异常处理，待处理:', err)
        }
    },

    start () {

    },

    // update (dt) {},
});
